package com.wensi.helper

import android.content.Context
import android.graphics.PixelFormat
import android.os.Build
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.WindowManager

/**
 * 窗口帮助类
 */
object WindowHelper {
    private lateinit var context: Context
    private lateinit var wm: WindowManager
    private lateinit var lp: WindowManager.LayoutParams

    fun initWindowHelper(context: Context) {
        this.context = context
        this.wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        lp = createLayoutParams()
    }
    // 创建布局属性
    fun createLayoutParams(): WindowManager.LayoutParams {
        val lp = WindowManager.LayoutParams()
        lp.apply {
            this.width = WindowManager.LayoutParams.MATCH_PARENT
            this.height = WindowManager.LayoutParams.MATCH_PARENT
            gravity = Gravity.CENTER
            format = PixelFormat.TRANSLUCENT
            flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or
                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
                    WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON or
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
            // >=   8.0
            type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
//                WindowManager.LayoutParams.TYPE_ACCESSIBILITY_OVERLAY
            else
                WindowManager.LayoutParams.TYPE_PHONE

        }

        return lp
    }

    // 获取视图控件
    fun getView(layoutId: Int): View {
        return View.inflate(context, layoutId, null)
    }

    // 显示窗口
    fun  showWindowView(view: View) {
        Log.e("=====com.wensi显示窗口=====", view.toString())
        if (view.parent == null) {
            wm.addView(view, lp)
        }
    }

    fun  showWindowView(view: View, lp: WindowManager.LayoutParams) {
        Log.e("=====com.wensi显示窗口=====", view.toString())
        if (view.parent == null) {
            wm.addView(view, lp)
        }
    }
    // 隐藏窗口
    fun  hideWindowView(view: View) {
        Log.e("=====com.wensi隐藏窗口=====", view.toString())
        if (view.parent != null) {
            // 不等于空，说明正在显示
            wm.removeView(view)
        }
    }
    // 更新视图
    fun updateWindowView(view: View, lp: WindowManager.LayoutParams) {
        wm.updateViewLayout(view, lp)
    }
}